package top.suven.base.http.admin.frame;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import top.suven.base.core.db.DataSourceGroupNameEnum;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Supplier;

public class DynamicDataSourceContextHolder {

    private static final Logger logger = LoggerFactory.getLogger(DynamicDataSourceContextHolder.class);

    /**
     * 用于在切换数据源时保证不会被其他线程修改
     */
    private static Lock lock = new ReentrantLock();

    /**
     * 用于轮循的计数器
     */
    private static int counter = 0;

    /**
     * Maintain variable for every thread, to avoid effect other thread
     */
    private static final ThreadLocal<Object> CONTEXT_HOLDER = ThreadLocal.withInitial(new Supplier<DataSourceGroupNameEnum>() {
        public DataSourceGroupNameEnum get() {
            return DataSourceGroupNameEnum.DATA_NAME_USER;
        }
    });
    /**
     * All DataSource List
     */
    public static List<Object> dataSourceKeys = new ArrayList<>();
    /**
     * To switch DataSource
     *
     * @param key the key
     */
    public static void setDataSourceKey(String key) {
        lock.lock();
        try {
            CONTEXT_HOLDER.set(key);
        } catch (Exception e) {
            logger.error("switch datasource failed, error message：", e);
        } finally {
            lock.unlock();
        }
    }

    /**
     * Get current DataSource
     *
     * @return data source key
     */
    public static String getDataSourceKey() {
        return CONTEXT_HOLDER.get().toString();
    }

    /**
     * To set DataSource as default
     */
    public static void clearDataSourceKey() {
        CONTEXT_HOLDER.remove();
    }
}
